package Consumer;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.util.ArrayList;

public class MyListener_var implements MessageListener {
    int num = 0;
    int N;
    double var = 0;
    ArrayList<Double> list = new ArrayList<>();
    MyListener_var(int N){
        this.N = N;
    }

    @Override
    public void onMessage(Message message) {
        try {
            num++;
            list.add(Double.valueOf(((TextMessage)message).getText()));
//            System.out.println("Received a message: "+((TextMessage)message).getText());
            if(num >= N){
                double sum = 0.0;
                for (int i = 0; i < N; i++) {
                    sum += list.get(i);
                }
                double mean = sum/N;
                for (double m: list) {
                    var += (m-mean) * (m-mean);
                }
                var /= N;
                list.remove(0);
                System.out.println("过去" + N +"个数的方差为："+ var);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
